package org.ihelpuoo.weboo.security;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.ihelpuoo.core.Nut;

public class Security
{

	public static Security me(Nut nut)
	{
		try
		{
			return (Security)nut.getObject(Security.class);
		}
		catch (Exception e)
		{
			return null;
		}
	}

	public static Security me(HttpServletRequest request)
	{
		return me(Nut.me(request.getSession().getServletContext()));
	}

	private Map<String, Integer>	nRoles;
	private Map<Integer, String>	vRoles;

	private String					failTarget;

	public String getFailTarget()
	{
		return failTarget;
	}

	public void setFailTarget(String failTarget)
	{
		this.failTarget = failTarget;
	}

	public Security()
	{
		nRoles = new HashMap<String, Integer>();
		vRoles = new HashMap<Integer, String>();
	}

	boolean addRole(String name, String value)
	{
		if (nRoles.containsKey(name))
			return false;
		Integer v = Integer.valueOf(value);
		if (vRoles.containsKey(v))
			return false;
		nRoles.put(name,v);
		vRoles.put(v,name);
		return true;
	}

	public Set<Integer> roleIds()
	{
		return vRoles.keySet();
	}

	public Set<String> roleNames()
	{
		return nRoles.keySet();
	}

	public int getRole(String name)
	{
		Integer v = nRoles.get(name);
		if (null == v)
			return -1;
		return v.intValue();
	}

	public String getName(int role)
	{
		return vRoles.get(role);
	}

	public int getRoleSize()
	{
		return nRoles.size();
	}

	public static final char[]	CODES	= {'1','2','3','4','5','6','7','8','9','0','A','B','C','D',
			'E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
}
